package com.zmxstudy.rbac.controller;



import cn.hutool.core.io.FileUtil;
import cn.hutool.http.HttpResponse;
import com.zmxstudy.rbac.vo.Result;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

//import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;


@RestController
@RequestMapping("/files")
public class FileController {

    @Value("${ip}")
    private String ip;

    @Value("${server.port}")
    private String port;
    private static final String ROOT_PATH = System.getProperty("user.dir") + "/files";


    @PostMapping("/upload")
    public Result upload( MultipartFile file){
        //获取文件的初始名
        String originalFilename = file.getOriginalFilename();
        //将时间戳绑定初始文件 避免造成文件的覆盖
        String filename = System.currentTimeMillis() +"_"+ originalFilename ;

        //最终存入磁盘的文件
        File finalFile = new File(ROOT_PATH + "/" + filename);
        //如果父级目录不存在 需创建
        if (!finalFile.getParentFile().exists()){
            finalFile.getParentFile().mkdir();
        }
        //存入文件
        try {
            file.transferTo(finalFile);
            System.out.println(finalFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
        //返回文件的url：
        String url = "http://"+ip+":" + port +"/files/download?filename=" + filename;
        return Result.build("00000","请求成功",url);
    }
    @GetMapping("/download")
    public void download( String filename, HttpServletResponse response){
        try {
            //设置响应头，告诉浏览器以附件（attachment）形式下载文件，并指定下载时的文件名
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));
            //设置响应的内容类型为二进制流
            response.setContentType("application/octet-stream");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        //找到磁盘图片
        File finalFile = new File(ROOT_PATH + "/" + filename);
        ServletOutputStream os = null;
        try {
            os = response.getOutputStream();
//            os = response.getOutputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        //将图片写入输出流
        FileUtil.writeToStream(finalFile, os);
        try {
            os.flush();
            os.close();
        } catch (IOException e) {
            e.printStackTrace();
        }



    }
}

